﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

namespace Common.DBUtility
{
    public class DbFactory
    {
        private static readonly Dictionary<string, Database> _databaseLookup =
            new Dictionary<string, Database>(StringComparer.InvariantCultureIgnoreCase);

        private static object _lockObject = new object();

        public DbFactory() { }

        private static Database GetDatabase(string dbName)
        {
            if (!_databaseLookup.ContainsKey(dbName))
            {
                lock (_lockObject)
                {
                    if (!_databaseLookup.ContainsKey(dbName))
                    {
                        _databaseLookup.Add(dbName, DatabaseFactory.CreateDatabase(dbName));
                    }
                }
            }
            return _databaseLookup[dbName];
        }


        public static DbHelper GetDbHelper(string dbName)
        {
            CheckDbName(dbName);
            return new DbHelper(GetDatabase(dbName));
        }


        private static void CheckDbName(string dbName)
        {
            if (string.IsNullOrEmpty(dbName))
                throw new ArgumentNullException("dbName", "the database can not be null");
        }
  

    }
}
